package com.example.lx1207.service.impl;

import com.example.lx1207.dao.DeptDao;
import com.example.lx1207.entity.Dept;
import com.example.lx1207.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author 荆豪峰
 * @version 1.0
 */
@Service
public class DeptImpl2 implements DeptService {
    @Autowired
    private DeptDao deptDao;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    /*
       cacheNames:缓存的名称
       key: 唯一区分 #id读取方法的参数名的值

     */
    @Override
    @Cacheable(cacheNames="redis::dept",key="#id")
    public Dept findById(Integer id) {
        Dept dept = deptDao.selectById(id);
        return dept;
    }

    @CacheEvict(cacheNames = "redis::dept",key = "#id")
    @Override
    public Integer delete(Integer id) {
        //只删除了数据库
        int i = deptDao.deleteById(id);

        return i;
    }

    @Override
    public Dept save(Dept dept) {
        deptDao.insert(dept);
        return dept;
    }

    @Override
    @CachePut(cacheNames = "redis::dept",key = "#dept.id")
    public Dept update(Dept dept) {
        //只修改数据库，但是缓存中的数据还是之前的。
        deptDao.updateById(dept);
        return dept;
    }
}
